#!/bin/bash
#################################################################
# @Description: 用例名称：支持大页内存运行虚拟机，测试目的：验证支持大页内存运行虚拟机
# @Date : 2023-11-24
# @Last Modified by :
# @Last Modified time: 2023-11-27
#################################################################
source "../common.sh"
export LANG=en_US.UTF-8
res=0

# 定义常量
HUGEPAGES_FILE="/proc/sys/vm/nr_hugepages"
SYSCTL_CONF="/etc/sysctl.conf"

# 指定配置文件路径
[ -f ${SYSCTL_CONF}-bak ] || cp ${SYSCTL_CONF} ${SYSCTL_CONF}-bak >/dev/null

# 新的 vm.nr_hugepages 设置
REQUIRED_HUGEPAGES=8

# 删除或注释掉旧的 vm.nr_hugepages 的设置
sed -i '/vm.nr_hugepages/d' "$SYSCTL_CONF" >/dev/null
# 添加新的 vm.nr_hugepages 的设置
echo "vm.nr_hugepages=$REQUIRED_HUGEPAGES" >> "$SYSCTL_CONF"

echo "执行命令： cat $SYSCTL_CONF | grep 'vm.nr_hugepages=8' 验证主机是否已经开启大页内存功能"
echo "程序未异常中断代表主机已经开启大页内存功能"
cat "$SYSCTL_CONF" | grep 'vm.nr_hugepages=8' 
if [ $? -ne 0 ];then
	  echo "Modify vm.nr_hugepages failed."
	  exit 1
fi

# 重新加载配置
sysctl -p >/dev/null

# 指定虚拟机文件路径
qcow2_file="/opt/vm1.qcow2"
vm5_name="vm5"
vm5_xml="/opt/${vm5_name}.xml"
cleanup_environment >/dev/null
echo "vm.nr_hugepages 的设置已更新为 $REQUIRED_HUGEPAGES，并已重新加载配置。"

echo "1.启用大页内存参数添加到虚拟机${vm5_xml}中"
cat /opt/${vm5_name}.xml | grep 'memorybacking' || { res=1; echo "memorybacking not in ${vm5_name}.xml."; exit 1; }
cat /opt/${vm5_name}.xml | grep 'hugepages' || { res=1; echo "hugepages not in ${vm5_name}.xml."; exit 1; }

echo "2.启动虚拟机${vm5_name}"
echo "开始执行命令：virsh define $vm5_xml"
virsh define "$vm5_xml" > /dev/null 2>&1 || { res=1; echo "$vm5_name define failed"; exit 1; }
echo "virsh define $vm5_xml 命令执行成功！"
echo "开始执行命令：virsh start $vm5_name"
virsh start "$vm5_name" > /dev/null 2>&1 || { res=1; echo "$vm5_name start failed"; exit 1; }
echo "virsh start $vm5_name 命令执行成功！"

echo ""
vnc_port5=$(virsh vncdisplay $vm5_name)
# 循环查询虚拟机的 IP 地址
echo "获取 VM5 IP 地址中·····"
while true; do
    ip_vm5=$(get_vm_ip "$vm5_name")
    # 如果有 IP 地址，打印信息并写入文件
    if [ -n "$ip_vm5" ]; then  
        check_and_ping $ip_vm5 && echo "虚拟机$vm5_name IP:$ip_vm5 启动正常！" || { ret=1; echo '虚拟机$vm5_name 启动失败'; }
        break  # 退出循环
    fi
    sleep 10
done

# 判断用例是否执行成功
[ "$res" = "0" ] && echo -e "\033[32m-----------------test PASSED----------------\033[0m" || echo -e "\033[31m-----------------test FAILED----------------\033[0m"
[ -f ${SYSCTL_CONF}-bak ] && \cp ${SYSCTL_CONF}-bak ${SYSCTL_CONF} 
# 重新加载配置
sysctl -p >/dev/null
